// 这是商品评价
import React, { useEffect, useState, } from 'react';
import { Input, Select, Space, Button, Table, Switch, ConfigProvider, Modal, Rate, message, } from 'antd';
import { ExclamationCircleFilled } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import '../../css/public.less' // 导入公共样式
import './css/GoodEvaluation.less' //自己写的页面样式
import { useNavigate } from 'react-router-dom'
import zh_CN from 'antd/es/locale/zh_CN';
import { classification } from '../../../api/ycl'
import { appraise } from '../../../api/ycl'
import { check } from '../../../api/ycl'
import { del } from '../../../api/ycl'
// 定义数据的格式
interface DataType {
    appraiseId: React.Key;
    goodsName: string; // 商品名称
    userName: string; // 用户昵称
    appraisePoint: string; //评分
    appraiseType: string; // 类型
    appraiseCreated: string; //时间
    appraiseStatus: string; // 是否显示
    appraiseContent: string;//评价的内容
    appraiseAdmin: string;//
    appraiseImg: string;//图片
    appraiseRep: string;//
    goodsSerNum: string;//序号
    orderId: string;//
    skuMsg: {}//
}
interface ListType {
    value: string,
    label: string
}
// 
const { confirm } = Modal
function GoodEvaluation() {
    const navigate = useNavigate()
    const [antistop, setAntistop] = useState<string | undefined>('') //获取到搜索框的内容
    const [classify, setClassify] = useState<string | undefined>('') //获取到商品分类的下拉框选择
    const [user, setUser] = useState<string | undefined>('') //获取到用户昵称里面的内容
    const [page, setPage] = useState<number>(1) //当前页
    const [limit, setLimit] = useState<number>(3) //当前页渲染多少条数据
    const [data, setData] = useState<DataType | any>()
    const [calss, setCalss] = useState<{}[]>() //搜索下拉的分类
    const [arr, setArr] = useState<[]>() // 删除的数组
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [count,setCount] = useState<number>(0)
    const [messageApi, contextHolder] = message.useMessage();

    const onChange = (e: boolean | number): void => { //点击是否显示获取到ture或者false
        console.log(e);
    };
    const shopId = (Items: DataType): void => { //点击上架获取到这一行的数据
        console.log(Items);

    }




    useEffect(() => {
        addclassification() // 获取所有分类的函数
        category() //全查类别

    }, [])

    const addclassification = async () => {
        let data = ({
            limit: limit,
            page: page
        })
        try {
            let res = await classification(data)
            console.log(res);
            
            if (res.code == '200') {
                setData(res.data.data)
                setCount(res.data.total)
            }
        } catch (err) {
            console.log('err', err);
        }
    }

    // 全查类别
    const category = async () => {
        try {
            let res = await check()
            if (res.code == '200') {
                let dataList = res.data.map((item: { categoryId: any; categoryName: any; }) => {
                    return { value: item.categoryId, label: item.categoryName }
                })
                setCalss(dataList)
            }
        } catch (err) {
            console.log(err);
        }
    }

    const columns: ColumnsType<DataType> = [
        {
            title: '商品名称',
            dataIndex: 'goodsName',
            align: 'center',
        },
        {
            title: '用户昵称',
            dataIndex: 'userName',
            align: 'center',
        },
        {
            title: '评分',
            dataIndex: 'appraisePoint',
            align: 'center',
            render: (_, record) => {
                return ( //这儿是评分星星
                    <Rate allowHalf defaultValue={Number(record.appraisePoint)} disabled={true} />
                )
            }
        },
        {
            title: '类型',
            dataIndex: 'appraiseType',
            align: 'center',
        },
        {
            title: '时间',
            dataIndex: 'appraiseCreated',
            align: 'center',
        },
        {
            title: '是否显示',
            dataIndex: 'appraiseStatus',
            align: 'center',
            render: (_, record) => {
                return ( //这个是加一个选中或者没选中的值defaultChecked
                    <Switch
                        onChange={onChange}
                        defaultChecked={record.appraiseStatus == '0'}
                        onClick={() => { shopId(record) }}
                    />
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'address',
            align: 'center',
            render: (_, record) => {
                return ( //这个是加一个选中或者没选中的值defaultChecked
                    <div>
                        <button className='edit' onClick={() => examine(record)}>查看</button>
                        <button className='del' onClick={() => showConfirm(record)}>删除</button>
                    </div>
                )
            }
        },
    ];

    // 搜索
    const search = (e: any): void => {
        setAntistop(e.target.value)
    }

    // 这是获取用户昵称的搜索框
    const searchUser = (e: any): void => {
        setUser(e.target.value)
    }

    // 下拉框的选择
    const handleChange = (value: string) => {

        setClassify(value)
    };

    // 筛选 获取到关键词，分类，昵称
    const screen = async (): Promise<void> => {
        let data = ({
            goodsName: antistop,
            categoryId: classify,
            userName: user,
            page: page,
            limit: limit
        })
        try {
            let res = await appraise(data)
            if (res.code == '200') {
                console.log(res.data);
                setData(res.data.data)
                setCount(res.data.total)
            }
        } catch (err) {
            console.log(err);
            setData([])
        }
    }

    // 重置
    const reset = (): void => {
        addclassification() // 获取所有分类的函数
    }

    // 查看
    const examine = (item: DataType): void => {
        navigate('/home/goods/GoodEvaluationDetail', { state: item }) //路由跳转传参数,本就可以只传一个id可以过来找,但是现在还没有后端数据现在是直接传输䣌一整串数据
    }

    

    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('id',newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;

    // 删除
    const showConfirm = (item: any) => {
        confirm({
            title: '删除',
            icon: <ExclamationCircleFilled />,
            content: '确定删除这个商品评价',
            async onOk() {
                // setArr(num(item.itemappraiseId))
                let data = [Number(item.appraiseId)]
                try {
                    let res = await del(data)
                    if (res.code == '200') {
                        messageApi.open({
                            type: 'success',
                            content: '删除成功',
                          });
                        addclassification()
                    }
                } catch (err) {
                    console.log(err);

                }
            },
            onCancel() {
            },
        });
    };

    // 页码
    const page1 = async (page: any, pageSize: any): Promise<void> => {
        let data = ({
            limit: pageSize,
            page: page
        })
        try {
            let res = await classification(data)
            console.log(res);
            if (res.code == '200') {
                setData(res.data.data)
                setCount(res.data.total)
            }
        } catch (err) {
            console.log('err', err);
        }
    }

    // 批量删除
    const batchDeletion =() =>{
        console.log(selectedRowKeys);
        confirm({
            title: '删除',
            icon: <ExclamationCircleFilled />,
            content: '确定删除所选中的商品评价',
            async onOk() {
                let data = selectedRowKeys
                try{
                    let res = await del(data)
                    if(res.code == '200'){
                        messageApi.open({
                            type: 'success',
                            content: '删除成功',
                          });
                        addclassification()
                    }
                }catch(err){
                    console.log(err);
                    
                }
            },
            onCancel() {
            },
        });
    }

    // 按照评分进行排序
    const handledate = async (value: string) => {
        let data = ({
            limit: limit,
            page: page,
            name: 'appraise_point',
            orderNum: 1
        })
        try {
            let res = await appraise(data)
            
            if (res.code == '200') {
                setData(res.data.data)
            }
        } catch (err) {
            console.log(err);

        }
    };

    return (
        // 头部区域
        
        <div className='GoodEvaluation'>
            {contextHolder}
            <div className='page-top'>
                <div className='page-title'>
                    <p>商品评价</p>
                </div>
            </div>

            {/* 表格区域 */}
            <div className='page-context'>
                <div className='evaluation-search'>
                    <p className='p'>筛选查询</p>
                    <div className='input'>

                        {/* 这里里面是关键词的搜索框 */}
                        <div className='input-search'>
                            <p>关键词</p>
                            <Input placeholder="商品名称/商品货号" onChange={search} />
                        </div>

                        {/* 这里面是商品分类的下拉框 */}
                        <div className='space'>
                            <p>商品分类</p>
                            <Space wrap>
                                <Select
                                    placeholder="商品分类"
                                    className='space-search'
                                    style={{ width: 120 }}
                                    allowClear
                                    onChange={handleChange}
                                    options={calss}
                                />
                            </Space>
                        </div>
                        {/* 这里面是用户昵称的搜素框 */}
                        <div className='input-search'>
                            <p>用户昵称</p>
                            <Input placeholder="用户昵称" onChange={searchUser} />
                        </div>
                    </div>
                    {/* 这里面是按钮 */}
                    <div className='buttom'>
                        <button className='reset' onClick={reset}>重置</button>
                        <button className='filter' onClick={screen}>筛选</button>
                    </div>
                </div>
                <div className='data-list'>
                    {/* 这里里面是表格 */}
                    <div className='ant-table'>
                        <div className='title'>
                            <p>数据列表</p>
                            <div className='sort'>
                                <p>排序方式</p>
                                <Select
                                    defaultValue="排序方式"
                                    className='select'
                                    onChange={handledate}
                                    style={{ width: 120 }}
                                    allowClear
                                    options={[
                                        { value: '按照评分排序', label: '按照评分排序' },
                                    ]}
                                />
                                <button className='batch-del' onClick={batchDeletion}>批量删除</button>
                            </div>

                        </div>
                        <ConfigProvider locale={zh_CN}>
                            <Table

                                rowSelection={rowSelection}
                                className='ant-table'
                                columns={columns}
                                dataSource={data}
                                scroll={{ y: 290 }}// 滚动设置成这样
                                rowKey={item => item.appraiseId}
                                
                                pagination={{
                                    onChange: page1,
                                    total:count,
                                    position: ['bottomCenter'],
                                    defaultPageSize: 3,                       // 如果页面只有一个表格，就默认展示10条
                                    pageSizeOptions: [3, 5, 10, 15],
                                    showQuickJumper: true,             // 快速跳转
                                    showSizeChanger: true,             // 页码改变
                                }}
                            />
                        </ConfigProvider>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default GoodEvaluation